import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Switch, message, Space, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import ApiService, { Homepage } from '../../services/api';
import SimpleRichTextEditor from '../SimpleRichTextEditor';

const { TextArea } = Input;

interface HomepageForm {
  title: string;
  content: string;
  is_published: boolean;
  is_active: boolean;
}

const HomepageManagement: React.FC = () => {
  const [homepages, setHomepages] = useState<Homepage[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingHomepage, setEditingHomepage] = useState<Homepage | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchHomepages();
  }, []);

  const fetchHomepages = async () => {
    try {
      setLoading(true);
      const data = await ApiService.getHomepages();
      setHomepages(data);
    } catch (error) {
      console.error('获取首屏列表失败:', error);
      message.error('获取首屏列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setEditingHomepage(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (homepage: Homepage) => {
    setEditingHomepage(homepage);
    form.setFieldsValue({
      title: homepage.title,
      content: homepage.content,
      is_published: homepage.is_published,
      is_active: homepage.is_active,
    });
    setModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await ApiService.deleteHomepage(id);
      message.success('删除成功');
      fetchHomepages();
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  const handlePublish = async (id: number) => {
    try {
      await ApiService.publishHomepage(id);
      message.success('发布成功');
      fetchHomepages();
    } catch (error) {
      console.error('发布失败:', error);
      message.error('发布失败');
    }
  };

  const handleSubmit = async (values: HomepageForm) => {
    try {
      if (editingHomepage) {
        await ApiService.updateHomepage(editingHomepage.id, values);
        message.success('更新成功');
      } else {
        await ApiService.createHomepage(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchHomepages();
    } catch (error: any) {
      console.error('操作失败:', error);
      message.error(error.message || '操作失败');
    }
  };

  const columns = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: '25%',
    },
    {
      title: '版本',
      dataIndex: 'version',
      key: 'version',
      width: '10%',
    },
    {
      title: '状态',
      key: 'status',
      width: '20%',
            render: (_: any, record: Homepage) => (
         <Space>
           {record.is_published && <Tag color="green">已发布</Tag>}
           {record.is_active && <Tag color="blue">启用</Tag>}
           {!record.is_active && <Tag color="red">禁用</Tag>}
         </Space>
       ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: '20%',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      width: '25%',
      render: (_: any, record: Homepage) => (
        <Space>
          <Button
            type="primary"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          {!record.is_published && (
            <Button
              type="default"
              size="small"
              onClick={() => handlePublish(record.id)}
            >
              发布
            </Button>
          )}
          {!record.is_published && (
            <Button
              type="default"
              size="small"
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleDelete(record.id)}
            >
              删除
            </Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div className="homepage-management">
      <div className="page-header">
        <h2>首屏管理</h2>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={handleCreate}
        >
          新建版本
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={homepages}
        rowKey="id"
        loading={loading}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      <Modal
        title={editingHomepage ? '编辑首屏' : '新建首屏'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="title"
            label="标题"
            rules={[{ required: true, message: '请输入标题!' }]}
          >
            <Input placeholder="请输入标题" />
          </Form.Item>

          <Form.Item
            name="content"
            label="内容"
            rules={[{ required: true, message: '请输入内容!' }]}
          >
            <SimpleRichTextEditor
              value={form.getFieldValue('content') || ''}
              onChange={(html: string) => form.setFieldValue('content', html)}
              height={400}
              placeholder="请输入富文本内容..."
            />
          </Form.Item>

          <Form.Item
            name="is_published"
            label="是否发布"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="is_active"
            label="是否启用"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingHomepage ? '更新' : '创建'}
              </Button>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default HomepageManagement; 